package com.fhao.controller;

import java.util.LinkedHashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson.JSONObject;
import com.ctc.wstx.util.StringUtil;
import com.fhao.feign.MemberServiceFeign;
import com.fuhao.api.entity.UserEntity;
import com.fuhao.base.ResponseBase;
import com.fuhao.constants.Constants;
import com.fuhao.utils.CookieUtil;
import com.qq.connect.QQConnectException;
import com.qq.connect.api.OpenID;
import com.qq.connect.javabeans.AccessToken;
import com.qq.connect.oauth.Oauth;
import com.sun.tools.classfile.Opcode.Set;

@Controller
public class LoginController {
	@Autowired
	private MemberServiceFeign memberFeign;
	
	//跳转到登陆页面
	@RequestMapping(value="/login",method=RequestMethod.GET)
	public String loginget() {
		return "login";
	}
	//#################账号密码登陆##################
	//请求具体实现
	@RequestMapping(value="/login",method=RequestMethod.POST)
	public String loginPost(UserEntity userEntity,HttpServletRequest request,HttpServletResponse response) {
		ResponseBase loginBase = memberFeign.login(userEntity);
		if(!loginBase.getCode().equals(Constants.HTTP_RES_CODE_200)) {
			request.setAttribute("error", "登陆失败");
			return "login";
		}
		LinkedHashMap map = (LinkedHashMap) loginBase.getData();
		String token = (String) map.get("token");
		if(StringUtils.isEmpty(token)) {
			request.setAttribute("error", "会话失效！");
		}
		setCookie(token, response);
		return "redirect:/";
	}
	//####################QQ登陆######################
	//生成qq登陆连接
	@RequestMapping("/getQQCode")
	public String getQQCode(HttpServletRequest request) throws QQConnectException {
		String authorizeUrl = new Oauth().getAuthorizeURL(request);
		//重定向到qq中
		return "redirect:"+authorizeUrl;
	}
	//qq回调地址
	@RequestMapping("/qqLoginCallback")
	public String qqLoginCallback(HttpServletRequest request,HttpSession session,HttpServletResponse response) throws QQConnectException {
		//底层封装了授权码，取获取accesstoken
		AccessToken accessTokenObj = new Oauth().getAccessTokenByRequest(request);
		if(accessTokenObj == null) {
			request.setAttribute("error", "QQ授权失败");
			return "error";
		}
		String accessToken = accessTokenObj.getAccessToken();
		if(StringUtils.isEmpty(accessToken)) {
			request.setAttribute("error", "accessToken为null");
			return "error";
		}
		//使用accesstoken获取openid
		OpenID openIDObj = new OpenID(accessToken);
		String openID = openIDObj.getUserOpenID();
		//使用openId查询数据库看是否关联账号
		ResponseBase findByOpenIdUser = memberFeign.findByOpenIdUser(openID);
		//未关联则跳转到关联账号页面
		if(findByOpenIdUser.getCode().equals(Constants.HTTP_RES_CODE_201)) {
			//把openid放入session，提供关联接口(qqRelation)保存到数据库中
			session.setAttribute("qqOpenid", openID);
			//跳转到关联账号页面
			return "qqrelation";
		}
		//已绑定账号,自动登陆，获取到认证token,
		LinkedHashMap map = (LinkedHashMap) findByOpenIdUser.getData();
		//并保存到cookie中
		String token = (String) map.get("token");
		setCookie(token, response);
		//跳转到首页
		return "index";
	}
	//跳到关联账号页面，提交关联信息接口，并把信息保存到数据库
	@RequestMapping(value="/qqRelation",method=RequestMethod.POST)
	public String qqRelation(UserEntity userEntity,HttpServletRequest request,HttpSession session,HttpServletResponse response) {
		//获取openid
		String openId = (String) session.getAttribute("qqOpenid");
		if(StringUtils.isEmpty(openId)) {
			request.setAttribute("error", "关联账号失败，openid为空");
			//跳转到错误页面中
			return "error";
		}
		//把获取到的openid放到用户实体中，远程调用qq登陆接口，把openid更新到用户数据库中
		userEntity.setOpenid(openId);
		ResponseBase loginBase = memberFeign.qqLogin(userEntity);
		if(!loginBase.getCode().equals(Constants.HTTP_RES_CODE_200)) {
			request.setAttribute("error", "登陆失败");
			return "login";
		}
		LinkedHashMap map = (LinkedHashMap) loginBase.getData();
		String token = (String) map.get("token");
		if(StringUtils.isEmpty(token)) {
			request.setAttribute("error", "会话失效！");
		}
		setCookie(token, response);
		return "redirect:/";
	}
	
	public void setCookie(String memberToken,HttpServletResponse response) {
		CookieUtil.addCookie(response, "cookie_member_token", memberToken, (int)60*60*24*90);
	}
}
